import React from 'react';
import PropTypes from 'prop-types';

/**
 * 文件导出组件，使用表单提交模式，后台返回文件流
 * @param {*} props
 */
function FileExport(props) {
  const { action, formData = [], children, uniqueId, style = {} } = props;

  const onDownload = e => {
    e.preventDefault();
    e.stopPropagation();
    document.getElementById(uniqueId || `download-${action}`).submit();
  };
  return (
    <span onClick={onDownload} style={{ display: 'inline-block', ...style }}>
      <form
        id={uniqueId || `download-${action}`}
        method="post"
        target="_blank"
        action={action}
      >
        {Object.entries(formData).map(item => {
          return (
            <input key={item[0]} type="hidden" name={item[0]} value={item[1]} />
          );
        })}
      </form>
      {children || null}
    </span>
  );
}

FileExport.defaultProps = {
  action: '',
  formData: {},
  style: {},
};

FileExport.propTypes = {
  action: PropTypes.string,
  formData: PropTypes.object,
  style: PropTypes.object,
};

export default FileExport;
